//
//  LoginViewController.m
//  ksjv2
//
//  Created by mac on 14/12/16.
//  Copyright (c) 2014年 CnbizMedia. All rights reserved.
//
//---------------------------------------------------------
//                    *              *
//                  *      登录界面     *
//                    *              *
//---------------------------------------------------------
#import "LoginViewController.h"
#import "ForgotPasswordViewController.h"
#import "Util.h"
#import "WXApi.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "UMSocial.h"
#import "AppDelegate.h"
#import "MobClick.h"
@interface LoginViewController ()<BDSocialUIDelegate,WXApiDelegate,TencentSessionDelegate,UIAlertViewDelegate>{
    float originY;
    TencentOAuth*ten;
    
    
    __weak IBOutlet UIButton *weixinButton;
    
    __weak IBOutlet UILabel *weixinLabel;
}
@end

@implementation LoginViewController
- (void)recvNotificationFromSina:(NSNotification*)notification{
    NSLog(@"LoginResponse:%@",notification.userInfo);
    if (notification.userInfo==nil) return;
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFY_SINA_WEIBO object:nil];
    [[AppAPIClient sharedClient] GET:@"https://api.weibo.com/2/users/show.json" parameters:@{@"source":KEY_SINA_WEIBO,@"access_token":notification.userInfo[@"access_token"],@"uid":notification.userInfo[@"uid"]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //NSLog(@"RESP:%@",responseObject);
        SHOW_LOADING;
        //[SVProgressHUD showWithStatus:LOADING_TEXT maskType:SVProgressHUDMaskTypeGradient];
        [[AppAPIClient sharedClient] POST:@"User/LoginOrSignupWithAccessToken" parameters:@{@"platform":@"sina",@"uid":notification.userInfo[@"uid"],@"username":responseObject[@"name"],@"gender":responseObject[@"gender"],@"baiduid":[UserDefaults objectForKey:@"baiduid"]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            int code = [responseObject[@"code"] intValue];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
            //[alert setTitle:@"提示"];
            NSLog(@"Response:login%@",responseObject);
            NSDictionary *user = responseObject[@"data"];
            if(code == 1){
                [alert setMessage:@"登录成功！"];
                NSString *token = user[@"token"];
                [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
                [UserDefaults setObject:user forKey:@"user"];
                [BPush setTag:token];
                
                
                
                //[AppAPIClient sharedClient].token = user[@"token"];
                [self popOfDismss];
            }
            [alert show];
            [SVProgressHUD showSuccessWithStatus:LOADING_TEXT_SUCCESS];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"ERROR:%@",operation.responseString);
            [SVProgressHUD showErrorWithStatus:LOADING_TEXT_ERROR];
        }];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
#pragma mark - SinaWeibo登录
- (void)doSinaWeiboLogin:(id)sender{
    [SVProgressHUD showWithStatus:@"正在登陆.." maskType:SVProgressHUDMaskTypeGradient];
//    [BDSocialShareSDK_Internal clearAllAuthorize];
//    [BDSocialShareSDK_Internal authorizeWithShareType:kBD_SOCIAL_SHARE_PLATFORM_SINAWEIBO supportedInterfaceOrientations:0 isStatusBarHidden:NO uiDelegate:self lightApiKey:KEY_SINA_WEIBO bduss:@"" result:^(BD_SOCIAL_RESULT requestResult, NSString *platformType, id response, NSError *error) {
//        if (requestResult!=BD_SOCIAL_SUCCESS) {
////            [SVProgressHUD showErrorWithStatus:@"登录失败"];
//            [SVProgressHUD dismiss];
//            return ;
//        }
    
    
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        //          获取微博用户名、uid、token等
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            NSLog(@"snsAccount %@",snsAccount);
//            NSDictionary*dic=response;
            //        NSLog(@"fffff_%@",dic);
//            NSString*baiduid=[[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"] == nil ? @"" : [[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"];
            
            /*username	字符串	账号
             password	字符串	密码
             type	数字	(可选)登录方式：使用百度的platform
             cid	字符串	(可选)第三方登陆数据
             nickname*/
            
            [[AppAPIClient sharedClient] POST:@"User/Login" parameters:@{@"username":snsAccount.userName,@"password":snsAccount.usid,@"cid":snsAccount.usid,@"type":@"Weibo",@"nickname":snsAccount.userName} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *user = responseObject[@"data"];
                NSString *token = user[@"token"];
                //            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
                NSString *overduedate = user[@"overduedate"];//时间戳
                [UserDefaults setObject:user forKey:@"user"];
                [UserDefaults setObject:token forKey:@"token"];
                [UserDefaults setObject:overduedate forKey:@"overduedate"];
                
                NSDictionary *usDic = [[NSDictionary alloc]initWithObjectsAndKeys:[user objectForKey:@"username"],@"username",snsAccount.usid,@"password", nil];
                [UserDefaults setObject:usDic forKey:@"usDic"];
                
                [BPush setTag:token];
                //            [alert setMessage:@"登录成功！"];
//                [MobClick profileSignInWithPUID:@"playerID" provider:@"WB"];//友盟登录统计
                [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
                [self popOfDismss];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];
        }
    
        else {
            [SVProgressHUD showErrorWithStatus:@"登录失败"];
            [SVProgressHUD dismiss];
        }
    });
    
   
//
        

//    }];
    
}

-(void)tencentDidNotNetWork{
    [SVProgressHUD showErrorWithStatus:@"无网络连接，请设置网络"];
}
-(void)tencentDidNotLogin:(BOOL)cancelled{
    if (cancelled)
    {
        [SVProgressHUD showErrorWithStatus:@"用户取消登录"];
//        _labelTitle.text = @"用户取消登录";
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"登录失败"];
//        _labelTitle.text = @"登录失败";
    }
}

- (void)tryTencentWebLogin{
    [SVProgressHUD showWithStatus:@"正在登陆.." maskType:SVProgressHUDMaskTypeGradient];
    
    ten=[[TencentOAuth alloc]initWithAppId:QQ_APP_KEY andDelegate:self];
    ten.redirectURI=@"www.qq.com";
    
    //    ten.localAppId=@"tencent100578511";
    //        [ten authorize:@[@"get_user_info", @"get_simple_userinfo"] ];
    
    
    [ten authorize:@[@"get_user_info", @"get_simple_userinfo"]inSafari:NO];
    
    

}

-(void)tencentDidLogin{
     [SVProgressHUD showWithStatus:@"登录完成" maskType:SVProgressHUDMaskTypeGradient];
//    [SVProgressHUD showErrorWithStatus:@"登录完成"];
//    _labelTitle.text = @"登录完成";
    if (ten.accessToken && 0 != [ten.accessToken length])
    {
        // 记录登录用户的OpenID、Token以及过期时间
//        _labelAccessToken.text = ten.accessToken;
        
        [ten getUserInfo];
        
    }
    else
    {
        [SVProgressHUD showWithStatus:@"登录不成功 没有获取accesstoken" maskType:SVProgressHUDMaskTypeGradient];
//        _labelAccessToken.text = @"登录不成功 没有获取accesstoken";
    }
    
}
-(void)getUserInfoResponse:(APIResponse *)response{
//    NSString*baiduid=[[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"] == nil ? @"" : [[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"];
    NSString*openId=ten.openId;
    NSString*nickname=response.jsonResponse[@"nickname"];
    if (openId==nil&&nickname==nil) {
        [SVProgressHUD showErrorWithStatus:@"登录失败"];
        return;
    }
    [[AppAPIClient sharedClient] POST:@"User/Login" parameters:@{@"username":ten.openId,@"password":openId,@"cid":openId,@"type":@"qq",@"nickname":nickname} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *user = responseObject[@"data"];
        NSString *tokenx = user[@"token"];
        [UserDefaults setObject:user forKey:@"user"];
        [UserDefaults setObject:tokenx forKey:@"token"];
        
        NSDictionary *usDic = [[NSDictionary alloc]initWithObjectsAndKeys:[user objectForKey:@"username"],@"username",openId,@"password", nil];
        [UserDefaults setObject:usDic forKey:@"usDic"];
        
        [BPush setTag:tokenx];
        [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
        [self popOfDismss];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"登录失败"];
    }];


}

#pragma mark - qq登录
- (void)doQQLogin:(id)sender{
    
//    ten=[[TencentOAuth alloc]initWithAppId:QQ_APP_KEY andDelegate:self];
//    ten.redirectURI=@"www.qq.com";
//    
////    ten.localAppId=@"tencent100578511";
//    [ten authorize:@[@"get_user_info", @"get_simple_userinfo"] ];

    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        //          获取qq用户名、uid、token等
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToQQ];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@ snsAccount is%@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL,snsAccount);
            
            [[AppAPIClient sharedClient] POST:@"User/Login" parameters:@{@"username":snsAccount.userName,@"password":snsAccount.usid,@"cid":snsAccount.usid,@"type":@"qq",@"nickname":snsAccount.userName} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"responseObject == %@",responseObject);
                NSDictionary *user = responseObject[@"data"];
                NSString *token = user[@"token"];
                //            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
                NSString *overduedate = user[@"overduedate"];//时间戳
                [UserDefaults setObject:user forKey:@"user"];
                [UserDefaults setObject:token forKey:@"token"];
                [UserDefaults setObject:overduedate forKey:@"overduedate"];
                
                NSLog(@"");
                NSDictionary *usDic = [[NSDictionary alloc]initWithObjectsAndKeys:[user objectForKey:@"username"],@"username",snsAccount.usid,@"password", nil];
                [UserDefaults setObject:usDic forKey:@"usDic"];
                
                [BPush setTag:token];
                //            [alert setMessage:@"登录成功！"];
//                [MobClick profileSignInWithPUID:@"playerID" provider:@"QQ"];//友盟登录统计
                [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
                [self popOfDismss];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];
        }
        
        else {
            [SVProgressHUD showErrorWithStatus:@"登录失败"];
            [SVProgressHUD dismiss];
        }

    
    
    });

//    [ten authorize:@[@"get_user_info", @"get_simple_userinfo"]inSafari:YES];
//    [BDSocialShareSDK_Internal clearAllAuthorize];
//    [BDSocialShareSDK_Internal authorizeWithShareType:kBD_SOCIAL_SHARE_PLATFORM_QQZONE supportedInterfaceOrientations:0 isStatusBarHidden:NO uiDelegate:self lightApiKey:QQ_APP_KEY bduss:@"" result:^(BD_SOCIAL_RESULT requestResult, NSString *platformType, id response, NSError *error) {
//        if (requestResult!=BD_SOCIAL_SUCCESS) {
////            [SVProgressHUD showErrorWithStatus:@"登录失败"];
//            return ;
//        }
//        NSDictionary*dic=response;
//        NSString*baiduid=[[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"] == nil ? @"" : [[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"];
//        [[AppAPIClient sharedClient] POST:@"User/Login" parameters:@{@"username":dic[@"name"],@"password":dic[@"media_uid"],@"cid":dic[@"media_uid"],@"type":dic[@"media_type"],@"baiduid":baiduid} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            NSDictionary *user = responseObject[@"data"];
//            NSString *token = user[@"token"];
//            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
//            [UserDefaults setObject:user forKey:@"user"];
//            [UserDefaults setObject:token forKey:@"token"];
//            [BPush setTag:token];
//            [alert setMessage:@"登录成功！"];
//            [self popOfDismss];
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            
//        }];
//
//        
//    }];
}
#pragma mark -
#pragma mark - 微信登录
-(void)sendStoryResponse:(APIResponse *)response{
    
}
-(void) onReq:(BaseReq*)req
{
    
}

-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendAuthResp class]])
    {
        SendAuthResp *temp = (SendAuthResp*)resp;
        if (temp.code==nil) {
            return;
        }
//        NSString *strTitle = [NSString stringWithFormat:@"Auth结果"];
//        NSString *strMsg = [NSString stringWithFormat:@"code:%@,state:%@,errcode:%d", temp.code, temp.state, temp.errCode];
        //NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WEIXIN_APP_KEY,WEIXIN_App_Secret,temp.code];
        
        [SVProgressHUD showWithStatus:@"正在登陆.." maskType:SVProgressHUDMaskTypeGradient];
        [[AppAPIClient sharedClient] POST:@"https://api.weixin.qq.com/sns/oauth2/access_token" parameters:@{@"appid":WEIXIN_APP_KEY,@"secret":WEIXIN_App_Secret,@"code":temp.code,@"grant_type":@"authorization_code"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"%@",responseObject);

            [self getWXUserInfoSetToken:responseObject[@"access_token"] setOpenID:responseObject[@"openid"]];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"ERR:%@",operation.responseString);
            [SVProgressHUD showErrorWithStatus:@"登录失败"];
        }];
        
    }
    
}

-( void )getWXUserInfoSetToken:(NSString*)token setOpenID:(NSString*)openid
{
    // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
    
    NSString *url =[NSString stringWithFormat:@ "https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@" ,token,openid];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//                self.nickname.text = [dic objectForKey:@ "nickname" ];
//                self.wxHeadImg.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:@ "headimgurl" ]]]];
                NSString*baiduid=[[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"] == nil ? @"" : [[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"];
                [[AppAPIClient sharedClient] POST:@"User/Login" parameters:@{@"username":openid,@"password":openid,@"cid":openid,@"type":@"weixin",@"baiduid":baiduid,@"nickname":[dic objectForKey:@"nickname"]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    if([responseObject[@"code"] intValue] == 1){
                        NSDictionary *user = responseObject[@"data"];
                        NSString *tokenx = user[@"token"];
                        [UserDefaults setObject:user forKey:@"user"];
                        [UserDefaults setObject:tokenx forKey:@"token"];
                        
                        NSDictionary *usDic = [[NSDictionary alloc]initWithObjectsAndKeys:[user objectForKey:@"username"],@"username",openid,@"password", nil];
                        [UserDefaults setObject:usDic forKey:@"usDic"];
                        
                        [BPush setTag:tokenx];
                        [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
                    }else{
                        [SVProgressHUD showErrorWithStatus:@"登录失败"];
                    }
                    
                    [self popOfDismss];
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    [SVProgressHUD showErrorWithStatus:@"登录失败"];
                }];
            }
        });
        
    });
}

-(void)doWEIXINLogin:(id)sender{
//    AppDelegate *a=(AppDelegate *)[[UIApplication sharedApplication] delegate];
//    a.LonginVC=self;
//    
//    SendAuthReq* req = [[SendAuthReq alloc] init];
//    req.scope = @"snsapi_userinfo"; // @"post_timeline,sns"
////    req.state = @"xxx";
////    req.openID = @"0c806938e2413ce73eef92cc3";
//    
//    [WXApi sendAuthReq:req viewController:self delegate:self];
    
    //判断是微信支付还是微信登陆
    [UserDefaults setObject:@"wxlogin" forKey:@"wx"];

    
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];
    
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        if (response.responseCode == UMSResponseCodeSuccess) {
            
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary]valueForKey:UMShareToWechatSession];
            
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            
            [[AppAPIClient sharedClient] POST:@"User/Login" parameters:@{@"username":snsAccount.userName,@"password":snsAccount.usid,@"cid":snsAccount.usid,@"type":@"WeiXin",@"nickname":snsAccount.userName} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *user = responseObject[@"data"];
                NSString *token = user[@"token"];
                //            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
                NSString *overduedate = user[@"overduedate"];//时间戳
                
                [UserDefaults setObject:user forKey:@"user"];
                [UserDefaults setObject:token forKey:@"token"];
                [UserDefaults setObject:overduedate forKey:@"overduedate"];
                
                NSDictionary *usDic = [[NSDictionary alloc]initWithObjectsAndKeys:[user objectForKey:@"username"],@"username",snsAccount.usid,@"password", nil];
                [UserDefaults setObject:usDic forKey:@"usDic"];
                
                [BPush setTag:token];
                //            [alert setMessage:@"登录成功！"];
//                [MobClick profileSignInWithPUID:@"playerID" provider:@"WX"];//友盟登录统计
                [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
                
                
                [self popOfDismss];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];
        }
        
        else {
            [SVProgressHUD showErrorWithStatus:@"登录失败"];
            [SVProgressHUD dismiss];
        }

        
    });
    
    
    
    
    
    
    
//    [BDSocialShareSDK_Internal clearAllAuthorize];
//    [BDSocialShareSDK_Internal authorizeWithShareType:kBD_SOCIAL_SHARE_PLATFORM_WEIXIN_SESSION supportedInterfaceOrientations:0 isStatusBarHidden:NO uiDelegate:self lightApiKey:WEIXIN_APP_KEY bduss:@"" result:^(BD_SOCIAL_RESULT requestResult, NSString *platformType, id response, NSError *error) {
//        if (requestResult!=BD_SOCIAL_SUCCESS) {
//            [SVProgressHUD showErrorWithStatus:@"登录失败"];
//            return ;
//        }
//        NSDictionary*dic=response;
//        NSString*baiduid=[[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"] == nil ? @"" : [[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"];
//        [[AppAPIClient sharedClient] POST:@"User/Login" parameters:@{@"username":dic[@"name"],@"password":dic[@"media_uid"],@"cid":dic[@"media_uid"],@"type":dic[@"media_type"],@"baiduid":baiduid} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            NSDictionary *user = responseObject[@"data"];
//            NSString *token = user[@"token"];
//            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
//            [UserDefaults setObject:user forKey:@"user"];
//            [UserDefaults setObject:token forKey:@"token"];
//            [BPush setTag:token];
//            [alert setMessage:@"登录成功！"];
//            [self popOfDismss];
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            
//        }];
//        
//
//    }];
}
#pragma mark -
- (void)viewDidLoad {
    [super viewDidLoad];
    //NSLog(@"Token:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"token"]);
 

    
    self.title=@"登录";
    self.userName.delegate = self;
    self.passWord.delegate = self;
    [self.userName addTarget:self action:@selector(nextOnKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.passWord addTarget:self action:@selector(nextOnKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidenKeyboard)];
    tap.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:tap];
    self.view.backgroundColor=UIColorFromRGB(0xf5f5f5);
    
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, 22, 22)];
    [button addTarget:self action:@selector(popOfDismss) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:[UIImage imageNamed:@"dismiss"] forState:UIControlStateNormal];
    
    NSString *newOldYear = [UserDefaults objectForKey:@"NewYear" ];
    if ([newOldYear isEqualToString:@"NewYear"]) {
        //状态栏的文字颜色换成白色
        
        [button setImage:[UIImage imageNamed:@"dismissGray"] forState:UIControlStateNormal];
        
    }
     UIBarButtonItem*leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem=leftBarItem;

    long int buttonNumber = 3;
    if (![WXApi isWXAppInstalled]) {
        buttonNumber--;
        
    }else if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]){
        buttonNumber--;
    }
    float x=self.view.frame.size.width/buttonNumber;
    float width = 40.0f;
    
    for (long int i=0; i<buttonNumber; i++) {
        UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(x * i + (x / 2 - width / 2),300,width,width)];
        [button setImage:[UIImage imageNamed:@"pp"] forState:UIControlStateNormal];
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(x * i + (x / 2 - 100 / 2), 350, 100, 22)];
        [label setFont:[UIFont systemFontOfSize:15]];
        [label setTextAlignment:NSTextAlignmentCenter];
        if(i==0){
                [button setImage:[UIImage imageNamed:@"ico06"] forState:UIControlStateNormal];
                label.text=@"微博登录";
                [button addTarget:self action:@selector(doSinaWeiboLogin:) forControlEvents:UIControlEventTouchUpInside];
         }
        
        if (i == 1 &&[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]){
                [button setImage:[UIImage imageNamed:@"ico07"] forState:UIControlStateNormal];
                label.text=@"QQ登录";
                [button addTarget:self action:@selector(doQQLogin:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        if (i == 2  ){
       
   
            if ([WXApi isWXAppInstalled]) {
                [button setImage:[UIImage imageNamed:@"weixin"] forState:UIControlStateNormal];
                label.text=@"微信登录";
                [button addTarget:self action:@selector(doWEIXINLogin:) forControlEvents:UIControlEventTouchUpInside];
            }
            
             else {
            
                 return;
            }
        }
    }
    
if ([[self.navigationController viewControllers] count]<2) {
////添加返回手势
    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
}
    
    
    [self findWeiXin];
}

- (void)findWeiXin{

    if ([WXApi isWXAppInstalled]) {
      
    }
    
    else {
        
        weixinButton.hidden = YES;
        weixinLabel.hidden  = YES;
        return;
    }

}


- (IBAction)weiboEvent:(id)sender {
    [self doSinaWeiboLogin:sender];
    
}

- (IBAction)QQEvent:(id)sender {
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
        [self doQQLogin:sender];
    }
    else{
//     [SVProgressHUD showSuccessWithStatus:@"您需要安装QQ"];
        [self tencentDidLogin ];
        [self tryTencentWebLogin];
    }
    
}

- (IBAction)wenxinEvent:(id)sender {
    if ([WXApi isWXAppInstalled]){
        
      [self doWEIXINLogin:sender];
        
    }
    else{
        [SVProgressHUD showSuccessWithStatus:@"您需要安装微信"];
    }
}

-(void)viewDidLayoutSubviews{
    UIView*view=[self.view viewWithTag:500];
    view.frame=CGRectMake((self.view.frame.size.width-view.frame.size.width)/2, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    
}
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        CATransition*transition=[CATransition animation];
        transition.duration=1;
        transition.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type=kCATransitionPush;
        transition.subtype=kCATransitionFromLeft;//方向
        [self.view.layer addAnimation:transition forKey:nil];
        [self popOfDismss];
//        [self dismissViewControllerAnimated:YES completion:^{
            [SVProgressHUD dismiss];
//        }];
        
    }
}
-(void)popOfDismss{
    if ([[self.navigationController viewControllers] count]>=2) {
//        self.hidesBottomBarWhenPushed = NO;
            [self.navigationController popViewControllerAnimated:YES];
        
    }else{
//    self.hidesBottomBarWhenPushed = NO;
    [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    //MainView
    [MobClick endLogPageView:@"LoginView"];
}

- (void)viewWillAppear:(BOOL)animated{
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [MobClick beginLogPageView:@"LoginView"];
}
- (IBAction)registered:(id)sender {
//    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    ForgotPasswordViewController*view=[story instantiateViewControllerWithIdentifier:@"ForgotPasswordViewController"];
//    [self.navigationController pushViewController:view animated:YES];
}
- (IBAction)ForgotPassword:(id)sender {
    NSString *account = self.userName.text;
    NSString *msg = @"";
    if([account length] > 0&&[CommonHelper isValidatePhone:account]){
        [SVProgressHUD show];
//        [SVProgressHUD showWithStatus:LOADING_TEXT maskType:SVProgressHUDMaskTypeGradient];
        [[AppAPIClient sharedClient] POST:@"User/FindPassword" parameters:@{@"mobile":account} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            int code = [[responseObject objectForKey:@"code"] intValue];
            if(code == 1){
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"新密码已发送" message:account delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                [SVProgressHUD dismiss];
            }else{
                
                [SVProgressHUD showErrorWithStatus:responseObject[@"message"]];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
    }else{
        msg = @"请输入手机号!";
    }
    if([msg length] > 0){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [SVProgressHUD dismiss];
}

- (IBAction)doLogin:(id)sender{
    if([self.userName.text length] > 1 && [self.passWord.text length] > 1){
        [SVProgressHUD show];
        
        NSString*baiduid=[[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"] == nil ? @"" : [[NSUserDefaults standardUserDefaults] objectForKey:@"baiduid"];
        [[AppAPIClient sharedClient] POST:@"User/Login" parameters:@{@"username":self.userName.text,@"password":self.passWord.text,@"baiduid":baiduid} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            int code = [responseObject[@"code"] intValue];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];
            //[alert setTitle:@"提示"];
            NSDictionary *user = responseObject[@"data"];
            if(code == 101){
                [alert setMessage:@"用户名不存在。"];
                [alert show];
            }else if(code == 100){
                [alert setMessage:@"用户信息不完整。"];
                [alert show];
            }else if(code == 102){
                [alert setMessage:@"用户密码无效。"];
                [alert show];
            }else if(code == 110){
                [alert setMessage:@"用户不存在。"];
                [alert show];
            }else if(code == 1){
                [alert setMessage:@"登录成功！"];
                NSString *token = user[@"token"];
                NSString *overduedate = user[@"overduedate"];//时间戳
                // [UMessage addAlias:self.userName.text type:@"USER_NAME" response:^(id responseObject, NSError *error) {
                 
                // }];
 
                [UserDefaults setObject:user forKey:@"user"];
                [UserDefaults setObject:token forKey:@"token"];
                [UserDefaults setObject:overduedate forKey:@"overduedate"];
                
                NSDictionary *usDic = [[NSDictionary alloc]initWithObjectsAndKeys:[user objectForKey:@"username"],@"username",self.passWord.text,@"password", nil];
                [UserDefaults setObject:usDic forKey:@"usDic"];
                
                [BPush setTag:token];
                [self popOfDismss];
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            }
            //            [alert show];
            
//            [SVProgressHUD showSuccessWithStatus:LOADING_TEXT_SUCCESS];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:LOADING_TEXT_ERROR];
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    if(originY == 0) originY = self.view.frame.origin.y;
    //NSLog(@"Y:%f",originY);
//    float width = self.view.frame.size.width;
//    float height = self.view.frame.size.height;
//    CGRect rect = CGRectMake(0, -50.0f, width, height);
    /*[UIView animateWithDuration:0.3f animations:^{
     self.view.frame = rect;
     }];*/
    return YES;
}

- (void)resumeView{
    if(originY == 0) return;
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    CGRect rect = CGRectMake(0, originY, width, height);
    [UIView animateWithDuration:0.3f animations:^{
        self.view.frame = rect;
    }];
}

-(void)hidenKeyboard{
    [self.userName resignFirstResponder];
    [self.passWord resignFirstResponder];
    [self resumeView];
}

- (IBAction)nextOnKeyboard:(UITextField*)sender{
    if(sender == self.userName){
        [self.passWord becomeFirstResponder];
    }else{
        [self hidenKeyboard];
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
